﻿using System.Text.Json;
using PC_Touch.DataOP;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace PC_Touch
{
    public partial class IOMonitorSetting : Form
    {
        public IOMonitorSetting()
        {
            InitializeComponent();
            x = this.Width;
            y = this.Height;
            setTag(this);
            this.Resize += new System.EventHandler(this.IOMonitor_Resize);

        }

        private void IOMonitor_Load(object sender, EventArgs e)
        {
            ReadMachineJson();
            ReadDBParameter();
        }
        JsonMachine jsonMachine;
        private void ReadMachineJson()
        {
            jsonMachine = JsonSerializer.Deserialize<JsonMachine>(File.ReadAllText(Environment.CurrentDirectory + @"/AppConfig/Machine.Json", Encoding.UTF8));
            textBox1.Text = jsonMachine.plcIP;
            textBox2.Text = jsonMachine.plcPort;
            textBox3.Text = jsonMachine.sleep.ToString();

        }
        private void WriteMachineJson()
        {
            jsonMachine.plcIP = textBox1.Text;
            jsonMachine.plcPort = textBox2.Text;
            jsonMachine.sleep = int.Parse(textBox3.Text);
            string json = JsonSerializer.Serialize(jsonMachine);
            File.WriteAllText(Environment.CurrentDirectory + @"/AppConfig/Machine.Json", json, Encoding.UTF8);
        }
        private void ReadDBParameter()
        {
           string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
           var helper = new SQLiteHelper<DBParameterShape>(connectionString);
           Func<IDataRecord, DBParameterShape> map = record =>
                       new DBParameterShape
                       {
                           id = record.GetInt32(0),
                           createDataTime = record.GetString(1),
                           dataName = record.GetString(2),
                           dataAddress = record.GetString(3),
                           dataType = record.GetString(4),
                           dataLength = record.GetInt32(5),
                           unit = record.GetString(6),
                           remark = record.GetString(7),
                       };
           var value = helper.Query("SELECT * FROM DBParameter", map);
           dataGridView1.DataSource = new BindingList<DBParameterShape>(value);
           dataGridView1.AllowUserToAddRows = true; // 允许添加新行
           dataGridView1.AllowUserToDeleteRows = true; // 允许删除行
           dataGridView1.EditMode = DataGridViewEditMode.EditOnEnter; // 设置编辑模式
           dataGridView1.Columns[0].ReadOnly = true;
            dataGridView1.Columns[1].ReadOnly = true;

            DataGridViewComboBoxColumn comboBoxColumn = new DataGridViewComboBoxColumn();
            comboBoxColumn.Name = "dataType";
            comboBoxColumn.HeaderText = "dataType";
            comboBoxColumn.DataPropertyName = "dataType"; // 数据绑定的列名
            dataGridView1.Columns.RemoveAt(4); // 移除原来的列
            dataGridView1.Columns.Insert(4, comboBoxColumn); // 插入新的下拉列
            List<string> categories = new List<string> { "Bool", "Short", "Int","Float","String" };
            comboBoxColumn.DataSource = categories;
            //comboBoxColumn.DisplayMember = "dataType"; // 显示的属性
            //comboBoxColumn.ValueMember = "dataType"; // 值的属性


            dataCount = dataGridView1.Rows.Count;
        }
        int dataCount = 0 ;
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            var row = dataGridView1.Rows[e.RowIndex];
            var p = row.DataBoundItem as DBParameterShape;
            string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
            DBParameterOP op = new DBParameterOP(connectionString);
            if (dataGridView1.Rows.Count > dataCount || dataGridView1.Rows.Count == 0)
            {
                op.AddParameterToDatabase(p);
            }
            else
            {
                op.UpdateParameterInDatabase(p);
            }
            ReadDBParameter();
        }

        private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to delete this row?", "Confirm Delete", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                var p = e.Row.DataBoundItem as DBParameterShape;
                string connectionString = $"Data Source={AppDomain.CurrentDomain.BaseDirectory}DataBase\\app.db;Cache=Shared";
                DBParameterOP op = new DBParameterOP(connectionString);
                op.DeleteParameterFromDatabase(p);
            }
        }

        #region 控件大小随窗体大小等比例缩放
        private float x = 1;//定义当前窗体的宽度
        private float y = 1;//定义当前窗体的高度
        private void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ";" + con.Height + ";" + con.Left + ";" + con.Top + ";" + con.Font.Size;
                if (con.Controls.Count > 0)
                {
                    setTag(con);
                }
            }
        }
        private void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                if (con.Tag != null)
                {
                    string[] mytag = con.Tag.ToString().Split(new char[] { ';' });
                    con.Width = Convert.ToInt32(System.Convert.ToSingle(mytag[0]) * newx);//宽度
                    con.Height = Convert.ToInt32(System.Convert.ToSingle(mytag[1]) * newy);//高度
                    con.Left = Convert.ToInt32(System.Convert.ToSingle(mytag[2]) * newx);//左边距
                    con.Top = Convert.ToInt32(System.Convert.ToSingle(mytag[3]) * newy);//顶边距
                    Single currentSize = System.Convert.ToSingle(mytag[4]) * newy;//字体大小
                    con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                    if (con.Controls.Count > 0)
                    {
                        setControls(newx, newy, con);
                    }
                }
            }
        }
        private void IOMonitor_Resize(object sender, EventArgs e)
        {
            float newx = (this.Width) / x;
            float newy = (this.Height) / y;
            setControls(newx, newy, this);
        }
        #endregion

        private void connPLCbutton_Click(object sender, EventArgs e)
        {
            WriteMachineJson();
        }
    }

}
